Skip to content

Mark the start vertex visited in BFS so it is not revisited - #95

Open
amalsaidov wants to merge 1 commit into
davecom:masterfrom
amalsaidov:fix-findallbfs-revisits-start
Open

amalsaidov wants to merge 1 commit into
davecom:masterfrom
amalsaidov:fix-findallbfs-revisits-start

Conversation

@amalsaidov

Copy link
Copy Markdown

Problem

bfs(fromIndex:goalTest:), bfs(fromIndex:toIndex:) and findAllBfs(fromIndex:goalTest:) in Sources/SwiftGraph/Search.swift never mark the start vertex as visited. On undirected graphs (and any graph with a cycle through the start) the start vertex is re-enqueued through an edge that leads back to it.

Repro

// undirected A-B-C
graph.findAllBfs(from: "A") { _ in true }
// returns 4 paths for 3 vertices: [], A->B, A->B->C, and a bogus A->B->A
// expected 3

Fix

Set visited[fromIndex] = true before queue.push(fromIndex) in the three BFS functions (3 lines). The DFS functions already mark visited on pop, so they are unaffected.

Test

testFindAllBfsDoesNotRevisitStartVertex added to Tests/SwiftGraphTests/SwiftGraphSearchTests.swift (and XCTestManifests.swift); it fails before the fix (4 != 3). Full swift test = 168 tests, 0 failures; swift build clean.

bfs(fromIndex:goalTest:), bfs(fromIndex:toIndex:) and findAllBfs never
marked the starting vertex as visited, so on graphs with cycles or
undirected edges it was re-enqueued. findAllBfs then reported the start
vertex twice (the second time with a bogus cycle path back to itself).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant